package com.yuerlive.rainbow.module.mine;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.design.widget.BottomSheetDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.yuerlive.rainbow.API;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.entity.EditedInfo;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.module.login.BindMobileActivity;
import com.yuerlive.rainbow.module.login.LoginActivity;
import com.yuerlive.rainbow.module.mine.presenter.EditContract;
import com.yuerlive.rainbow.module.mine.presenter.EditPresenter;
import com.yuerlive.rainbow.module.recharge.RechargeActivity;
import com.yuerlive.rainbow.nim.NimHelper;
import com.yuerlive.rainbow.utils.FileUploadUtil;
import com.yuerlive.rainbow.utils.FileUtil;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.ToastUtils;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.utils.Utils;
import com.yuerlive.rainbow.widget.CircleImageView;
import com.yuerlive.rainbow.widget.CustomBottomSheetDialog;
import com.yuerlive.rainbow.widget.CustomDialog;
import com.yuerlive.rainbow.widget.timeselector.ConstellationUtil;
import com.yuerlive.rainbow.widget.timeselector.TextUtil;
import com.yuerlive.rainbow.widget.timeselector.TimeSelector;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiaoyi on 2017/5/17.
 */

public class MyInfoActivity extends BaseActivity<EditContract.Presenter> implements EditContract.View {
    private static final String title = "我的资料";
    @BindView(R.id.imgHeader)
    CircleImageView imgHeader;
    @BindView(R.id.tvId)
    TextView tvId;
    @BindView(R.id.tvNickName)
    TextView tvNickName;
    @BindView(R.id.tvSex)
    TextView tvSex;
    @BindView(R.id.tvAge)
    TextView tvAge;
    @BindView(R.id.tvMobile)
    TextView tvMobile;
    @BindView(R.id.tvSign)
    TextView tvSign;
    @BindView(R.id.tvIdTips)
    TextView tvIdTips;
    @BindView(R.id.tvMobileTips)
    TextView tvMobileTips;
    private TimeSelector timeSelector;
    private BottomSheetDialog bottomSheetDialog;
    private BottomSheetDialog editSexDialog;
    private String filename; // 图片名称
    private File outputImage;
    private Uri imageUri; // 图片路径
    private static final int REQUEST_TAKE_PHOTO = 3;
    private static final int REQUEST_CROP_PHOTO = 4;
    private HashMap<String, String> params = new HashMap<>();
    private CustomDialog dialog;
    public static final int BIRTHDAY = 1;
    public static final int ICON = 2;
    public static final int MOBILE = 3;
    public static final int NICKNAME = 4;
    public static final int PERSONSIGNATURE = 5;
    public static final int SEX = 6;
    public static final int REQUEST_CODE = 100;
    public static final int BING_MOBILE_REQUEST = 7;
    private EditedInfo info;
    private String mFilePath;
    private String mFileName;
    private String mPDFPath;
    private User user;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FileUploadUtil.SUCCESS:
                    //   hideLoading();
                    try {
                        Bundle resultData = msg.getData();
                        String result = resultData.getString("result");
                        JSONObject object = new JSONObject(result);
                        if (!TextUtils.isEmpty(object.getString("object").toString())) {
                            String imgName = object.getString("object").toString();
                            info = new EditedInfo();
                            info.setType(ICON);
                            info.setIcon(imgName);
                            presenter.getEditRequest(info);
                        } else {
                            showSnackbar(getRootView(mActivity), "上传失败", 0);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case FileUploadUtil.FAILED:
                    // hideLoading();
                    showSnackbar(getRootView(mActivity), "上传失败", 0);
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_myinfo;
    }

    @Override
    protected void initViews() {
        timeSelector();
        user = UserProxy.getUser();
        if (user == null) {
            jumpToActivity(LoginActivity.class);
            return;
        } else {
            setData();
        }
        setTitle(title);
        presenter = new EditPresenter(this);
        FileUtil.init();
        mFilePath = FileUtil.getFileDir() + File.separator;
        mPDFPath = FileUtil.getFileDir() + File.separator + "abc.pdf";
    }

    private void setData() {
        GlideUtil.load(this, user.getUserInfo().getIcon(), imgHeader);
        if (!TextUtils.isEmpty(user.getUserInfo().getId())) {
            tvId.setText(user.getUserId());
        } else {
            tvIdTips.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
        tvNickName.setText(user.getUserInfo().getNickname());
        tvSex.setText(user.getUserInfo().getSex() == 0 ? "男" : "女");
        //TODO 设置星座年龄
        if (!TextUtils.isEmpty(user.getUserInfo().getMobile())) {
            tvMobile.setText(user.getUserInfo().getMobile());
        } else {
            tvMobileTips.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_right, 0);
            tvMobile.setText("未绑定");
        }
        if (!TextUtil.isEmpty(user.getUserInfo().getPersonalsignature())) {
            tvSign.setText(user.getUserInfo().getPersonalsignature());
        } else {
            tvSign.setText("这个家伙很懒，什么都没有说");
        }
        if (!TextUtil.isEmpty(user.getUserInfo().getBirthDate())) {
            Calendar mycalendar = Calendar.getInstance();//获取现在时间
            String nowyear = String.valueOf(mycalendar.get(Calendar.YEAR));//获取年份
            // 用文本框输入年龄
            int age = Integer.parseInt(nowyear);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                java.util.Date date = format.parse(user.getUserInfo().getBirthDate());// 构造开始日期
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                tvAge.setText((age - year) + "  " + ConstellationUtil.getConstellation(month, day));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            tvAge.setText("");
        }
    }

    @OnClick({R.id.rlAge, R.id.rlEditHeader, R.id.rlEditNickName, R.id.rlSex, R.id.rlSign, R.id.rlMobile})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlAge:
                show();
                break;
            case R.id.rlEditHeader:
                showOrHiddenBottomSheetDialog();
                break;
            case R.id.rlEditNickName:
                showEditNickNameDialog();
                break;
            case R.id.rlSex:
                editSexDialog();
                break;
            case R.id.rlSign:
                jumpToActivityForResult(MySignActivity.class, REQUEST_CODE);
                break;
            case R.id.rlMobile:
                if (TextUtil.isEmpty(user.getUserInfo().getMobile())) {
                    jumpToActivityForResult(BindMobileActivity.class, BING_MOBILE_REQUEST);
                }
                break;
        }

    }

    /**
     *
     *
     */
    private void showEditNickNameDialog() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_edit_nickname, null);
        dialog = new CustomDialog(mActivity, contentView);
        RelativeLayout rlInput = (RelativeLayout) contentView.findViewById(R.id.rlInput);
        TextView tvTitle = (TextView) contentView.findViewById(R.id.tvTitle);
        final ImageView ivClear = (ImageView) contentView.findViewById(R.id.ivClear);
        final EditText etInput = (EditText) contentView.findViewById(R.id.etInput);
        TextView tvCancle = (TextView) contentView.findViewById(R.id.tvCancle);
        TextView tvSure = (TextView) contentView.findViewById(R.id.tvSure);
        ivClear.setVisibility(View.GONE);
        tvTitle.setText(getResources().getString(R.string.modify_nickname));
        ivClear.setVisibility(View.GONE);
        popupInputMethodWindow();
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etInput.setText("");
            }
        });
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.isEmpty(etInput.getText().toString().trim())) {
                    showSnackbar(getRootView(mActivity), "昵称不能为空", 0);
                    return;
                }
                //Todo 网络请求修改名字
                info = new EditedInfo();
                info.setType(NICKNAME);
                info.setNickname(etInput.getText().toString());
                presenter.getEditRequest(info);
                dialog.dismiss();
            }
        });
    }

    private void popupInputMethodWindow() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) MyInfoActivity.this.getSystemService(Service.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 0);
    }

    private void editSexDialog() {
        if (editSexDialog == null) {
            CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(this);
            View contentView = View.inflate(this, R.layout.bottom_sheet_dilaog, null);
            editSexDialog = dialog.getInstance(contentView);
            TextView tvOpenPhoto = (TextView) contentView.findViewById(R.id.tvOpenPhoto);
            tvOpenPhoto.setText("男");
            tvOpenPhoto.setOnClickListener((view) -> {
                info = new EditedInfo();
                info.setType(SEX);
                info.setSex(String.valueOf(0));
                presenter.getEditRequest(info);
                editSexDialog.dismiss();
            });
            TextView tvOpenPictrue = (TextView) contentView.findViewById(R.id.tvOpenPictrue);
            tvOpenPictrue.setText("女");
            tvOpenPictrue.setOnClickListener((view) -> {
                info = new EditedInfo();
                info.setType(SEX);
                info.setSex(String.valueOf(1));
                presenter.getEditRequest(info);
                editSexDialog.dismiss();
            });
            TextView tvCancle = (TextView) contentView.findViewById(R.id.tvCancle);
            tvCancle.setOnClickListener((view) -> {
                editSexDialog.dismiss();
            });
        }
        editSexDialog.show();
    }

    private void showOrHiddenBottomSheetDialog() {
        if (bottomSheetDialog == null) {
            CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(this);
            View contentView = View.inflate(this, R.layout.bottom_sheet_dilaog, null);
            bottomSheetDialog = dialog.getInstance(contentView);
            contentView.findViewById(R.id.tvOpenPhoto).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvOpenPictrue).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvCancle).setOnClickListener(clickListener);
        }
        bottomSheetDialog.show();
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //请求照相机权限
            if (!checkPermissions(new String[]{Manifest.permission.CAMERA})) {
                requestPermission(new String[]{Manifest.permission.CAMERA}, 0x0001);
                return;
            }
            switch (v.getId()) {
                case R.id.tvOpenPhoto:
                    openCamera();
                    break;
                case R.id.tvOpenPictrue:
                    takeAlbum();
                    break;
            }
            if (bottomSheetDialog != null && bottomSheetDialog.isShowing()) {
                bottomSheetDialog.dismiss();
            }
        }
    };

    private void takeAlbum() {
        Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        getAlbum.setType("image/*");
        startActivityForResult(getAlbum, 5);
    }
    //TODO 解决7.0 FileUriExposedException 问题  但是裁剪图片的时候获取不到数据   暂时不知道为什么
//    public void jump2Camera() {
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            File path = new File(mFilePath);
//            if (!path.exists()) {
//                path.mkdirs();
//            }
//            mFileName = System.currentTimeMillis() + ".jpg";
//            File file = new File(path, mFileName);
//            if (file.exists()) {
//                file.delete();
//            }
//            imageUri=FileUtil.getUriForFile(this,file);
//            FileUtil.startActionCapture(this,file,REQUEST_TAKE_PHOTO);
//
//        } else {
//            L.e("main","sdcard not exists");
//        }
//    }

    private void openCamera() {
        // 图片名称 时间命名
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        filename = format.format(date);
        // 创建File对象用于存储拍照的图片 SD卡根目录
        // 存储至DCIM文件夹
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        outputImage = new File(path, filename + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将File对象转换为Uri并启动照相程序
        imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); // 照相
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // 指定图片输出地址
        startActivityForResult(intent, REQUEST_TAKE_PHOTO); // 启动照相
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            Intent intent = new Intent("com.android.camera.action.CROP"); // 剪裁
            intent.setDataAndType(imageUri, "image/*");
            intent.putExtra("scale", true);
            // 设置宽高比例
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            // 设置裁剪图片宽高
            intent.putExtra("outputX", 200);
            intent.putExtra("outputY", 200);
            intent.putExtra("return-data", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // 广播刷新相册
            Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intentBc.setData(imageUri);
            this.sendBroadcast(intentBc);
            startActivityForResult(intent, REQUEST_CROP_PHOTO); // 设置裁剪参数显示图片至ImageView
        } else if (requestCode == REQUEST_CROP_PHOTO && resultCode == RESULT_OK) {

            L.e(TAG, "RESULT_OK");
            if (data != null && data.getExtras() != null) {
                Bitmap b = (Bitmap) data.getExtras().get("data");
                if (b != null) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = new Date(System.currentTimeMillis());
                    filename = format.format(date);
                    // 创建File对象用于存储拍照的图片 SD卡根目录
                    // 存储至DCIM文件夹
                    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    outputImage = new File(path, filename + ".jpg");
                    try {
                        if (outputImage.exists()) {
                            outputImage.delete();
                        }
                        outputImage.createNewFile();
                        L.e(TAG, "RESULT_OK" + outputImage);
                        b.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(outputImage));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            uploadUserHead();
        } else if (requestCode == 5) {
            if (data != null) {
                startPhotoZoom(data);
            }
        } else if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            String content = data.getStringExtra("signContent");
            tvSign.setText(content);
            if (UserProxy.getUser() != null) {
                User user = UserProxy.getUser();
                user.getUserInfo().setPersonalsignature(content);
                UserProxy.setUser(user);
            }
        } else if (requestCode == BING_MOBILE_REQUEST && resultCode == RESULT_OK && data != null) {
            tvMobile.setText(data.getStringExtra("mobile"));
        }
    }

    private void startPhotoZoom(Intent data) {

        Uri uri = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            //这里如果是false，就是旧版本的uri
            if (DocumentsContract.isDocumentUri(this, data.getData())) {
                String path = FileUtil.getPath(this, data.getData());
                uri = FileUtil.pathToUri(path);
            }else {
                uri = data.getData();
            }
        } else {
            /**
             * 这里selectImage需要传的data是onActivityResult的返回,
             * 当然你也可以在这里不做处理，这里会采用系统默认的uri ,并不会
             * 转义,我实际项目中没有做这里的else判断，使用默认的uri,即返回的
             * data.getData()
             */
            String path = FileUtil.selectImage(this, data);
            uri = FileUtil.pathToUri(path);
        }

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");

        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 4);
        // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    private void uploadUserHead() {
        params.clear();
        final Map<String, String> fileParams = new HashMap<>();
        fileParams.put("pic", outputImage.getAbsolutePath());
        User user = UserProxy.getUser();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //上传剪切后的照片
                FileUploadUtil.uploadImageFile(API.HOST + API.UPLOAD_PIC, params, fileParams, mHandler);
            }
        }).start();
    }

    private void timeSelector() {
        timeSelector = new TimeSelector(this, new TimeSelector.ResultHandler() {
            @Override
            public void handle(String time, String age, String constellation) {
                info = new EditedInfo();
                info.setType(BIRTHDAY);
                info.setAge(age);
                info.setConstellation(constellation);
                info.setBirthday(time);
                presenter.getEditRequest(info);
            }
        }, "1950-01-01 00:00", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));

        timeSelector.setScrollUnit(TimeSelector.SCROLLTYPE.YEAR, TimeSelector.SCROLLTYPE.MONTH, TimeSelector.SCROLLTYPE.DAY);
    }


    public void show() {
        User user = UserProxy.getUser();
        if (TextUtil.isEmpty(user.getUserInfo().getBirthDate())) {
            timeSelector.show();
        } else {
            timeSelector.show(user.getUserInfo().getBirthDate());
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeSelector != null) {
            timeSelector.release();
        }
    }

    @Override
    public void showResutl(BaseData baseData, int type) {
        User user = UserProxy.getUser();
        if (baseData.getCode() == 0) {
            switch (type) {
                case BIRTHDAY:
                    tvAge.setText(info.getAge() + "    " + info.getConstellation());
                    user.getUserInfo().setBirthDate(info.getBirthday() + " 00:00:00");
                    break;
                case ICON:
                    GlideUtil.load(this, info.getIcon(), imgHeader);
                    NimHelper.updateUserInfo(UserInfoFieldEnum.AVATAR, info.getIcon());
                    user.getUserInfo().setIcon(info.getIcon());
                    break;
                case MOBILE:
                    break;
                case NICKNAME:
                    if (!TextUtil.isEmpty(info.getNickname())) {
                        tvNickName.setText(info.getNickname());
                        user.getUserInfo().setNickname(info.getNickname());
                        NimHelper.updateUserInfo(UserInfoFieldEnum.Name, info.getNickname());
                    }
                    break;
                case PERSONSIGNATURE:
                    break;
                case SEX:
                    tvSex.setText("0".equals(info.getSex()) ? "男" : "女");
                    user.getUserInfo().setSex(Integer.parseInt(info.getSex()));
                    break;
            }
            UserProxy.setUser(user);
        } else {
            showSnackbar(getRootView(mActivity), baseData.getResult(), 0);
        }
    }

    @Override
    public void setPresenter(EditContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }
}
